package dispatcher.group.gui.elevator;

import java.util.ArrayList;

/**
 * This class is a custom synchronized ArrayList. This class will keep a list of elevator panels.
 * The adding of and ElevatorPanel is only successful if there is not another ElevatorPanel with the
 * same ID.
 * <p>
 * <b>*NOTE* : </b>The only methods that are thread safe are 
 * <code>add(ElevatorPanel)</code> and <code>remove(int)</code>.
 * For other thread safe method please refer to the ArrayList documentation
 *  
 * @author Caleb
 *
 */
public class ElevatorPanelList extends ArrayList<ElevatorPanel> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3796605617901877824L;

	
	/**
	 * A thread save add method
	 * @param panel The elevator panel to be added
	 * @return Returns true of the add was successful
	 */
	@Override
	public synchronized boolean add(ElevatorPanel panel){
		
		for(int i = 0; i < this.size(); i++){
			synchronized(this.get(i)){
				if (this.get(i).getElevatorId() == panel.getElevatorId()){
					return false;
				}
			}
		}
		
		return super.add(panel);
	}
	
	/**
	 * A thread save remove method
	 * @param id The elevator ID to be removed
	 * @return Returns the panel that was removed
	 */
	@Override
	public synchronized ElevatorPanel remove(int id){
		
		ElevatorPanel panel = null;
		
		for(int i = 0; i < this.size(); i++){
			synchronized(this.get(i)){
				if (this.get(i).getElevatorId() == id){
					panel = this.get(i);
				}
			}
		}
		if (super.remove(panel) == false){
			return null;
		}
		return panel;
	}
}
